import * as React from 'react'
import { Toast } from 'antd-mobile'
import { Gird, NavBar, Button } from 'components'
import './index.less'
import { post } from '../../../utils'

export default class ReName extends React.Component<any, any> {
    public state = {
        editStatus: false
    }
    
    private name: string = ''

    public render(): JSX.Element {
        const { userInfo } = this.props
        return (
            <div className="account">
                <NavBar title="修改昵称" />
                <Gird style={{ marginTop: 0 }}>
                    <Gird.Input className="account_input" value={userInfo.nick_name} onChange={this.handleChange} onClose={this.handleClose} />
                </Gird>
                <div className="account_re_name">4-20个字符，可有中英文、数字、“-”“_””组成</div>
                <Button className="btn" disabled={(userInfo.nick_name && userInfo.nick_name !== this.name) ? false : true} onClick={this.handleReSet}>保存修改</Button>
            </div>
        )
    }

    public componentWillMount() {
        const { userInfo } = this.props
        this.name = userInfo.nick_name
    }

    public componentWillUnmount() {
        const { userInfo, SET_USER_INFO } = this.props
        const { editStatus } = this.state
        if (!editStatus) {
            SET_USER_INFO({
                ...userInfo,
                nick_name: this.name
            })
        }
    }

    private handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const { SET_USER_INFO, userInfo } = this.props
        const value = { ...userInfo, nick_name: e.target.value }
        SET_USER_INFO(value)
    }

    private handleClose = () => {
        const { SET_USER_INFO, userInfo } = this.props
        const value = { ...userInfo, nick_name: '' }
        SET_USER_INFO(value)
    }

    private handleReSet = () => {
        const { userInfo, history } = this.props
        post('usersapi/userNickName', {
            userId: userInfo.id,
            nick_name: userInfo.nick_name
        }).then((data: any) => {
            Toast.info('昵称修改成功', 2)
            setTimeout(() => { this.setState({ editStatus: true }); history.goBack() }, 2000)
        })
    }
}